package com.egao.common.module.company.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.egao.common.core.utils.ReadJsonUtil;
import com.egao.common.module.company.utils.entity.PositionAddress;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 职位地址工具类
 * @author lym
 * @date 2024/8/23 16:13
 */
public class PositionAddressUtil {

    /**
     * 匹配学生选择地址和单位地址
     * @param studentAddressName 学生职位
     * @param companyAddressName 单位职位
     * @return boolean
     */
    public static boolean matching(String studentAddressName, String companyAddressName) {
        String[] companyAddressNames = companyAddressName.split(",");
        for (int i = 0; i < companyAddressNames.length; i++) {
            if (studentAddressName.contains(companyAddressNames[i])) {
                return true;
            }
        }

        String positionAddressJson = ReadJsonUtil.readJsonFromResource("json/positionAddress.json");
        List<PositionAddress> positionAddressList = JSONUtil.toList(positionAddressJson, PositionAddress.class);

        List<String> studentList = Arrays.stream(studentAddressName.split(",")).collect(Collectors.toList());
        List<String> companyList = Arrays.stream(companyAddressName.split(",")).collect(Collectors.toList());

        List<String> addStudent = new ArrayList<>();
        studentList.forEach(d -> {
            String res = findTop(d, positionAddressList);
            if (!StrUtil.isBlank(res)) {
                addStudent.add(res);
            }
        });
        studentList.addAll(addStudent);

        List<String> addCompany = new ArrayList<>();
        companyList.forEach(d -> {
            String res = findTop(d, positionAddressList);
            if (!StrUtil.isBlank(res)) {
                addCompany.add(res);
            }
        });
        companyList.addAll(addCompany);

        for (String s : studentList) {
            for (String c : companyList) {
                if (s.equals(c)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 找出顶级地址
     * @param address 地址
     * @param list 地址集合
     * @return
     */
    private static String findTop(String address, List<PositionAddress> list) {
        for (PositionAddress item1 : list) {
            if (CollectionUtil.isEmpty(item1.getChildren())) {
                continue;
            }

            for (PositionAddress item2 : item1.getChildren()) {
                if (item2.getName().equals(address)) {
                    return item1.getName();
                }
            }
        }
        return null;
    }
}
